from flask import Flask, jsonify, request, render_template_string
from flask_cors import CORS
import requests
import re

app = Flask(__name__)
CORS(app)

# 完整的HTML界面代码
HTML_CONTENT = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>短剧搜索平台</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; }
        .container { max-width: 800px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .search-box { display: flex; gap: 10px; margin-bottom: 20px; }
        #search-input { flex: 1; padding: 12px; border: 1px solid #ddd; border-radius: 5px; font-size: 16px; }
        #search-button { padding: 12px 24px; background: #007cba; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; }
        .result-card { border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 5px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎬 短剧搜索平台</h1>
        <p>搜索百度网盘、夸克网盘资源</p>

        <div class="search-box">
            <input type="text" id="search-input" placeholder="输入短剧名称，如：撕夜">
            <button id="search-button">搜索</button>
        </div>

        <div id="results"></div>
    </div>

    <script>
        const API_BASE_URL = window.location.origin;

        document.getElementById('search-button').addEventListener('click', performSearch);
        document.getElementById('search-input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') performSearch();
        });

        function performSearch() {
            const query = document.getElementById('search-input').value.trim();
            const resultsDiv = document.getElementById('results');

            if (!query) {
                resultsDiv.innerHTML = '<p style="color: red;">请输入搜索关键词</p>';
                return;
            }

            resultsDiv.innerHTML = '<p>搜索中...</p>';

            fetch(`${API_BASE_URL}/search?name=${encodeURIComponent(query)}`)
                .then(response => response.json())
                .then(data => {
                    if (data.data && data.data.length > 0) {
                        let html = '<h3>搜索结果：</h3>';
                        data.data.forEach(item => {
                            html += `
                                <div class="result-card">
                                    <strong>${item.name}</strong><br>
                                    <small>来源: ${item.source}</small><br>
                                    <a href="${item.url}" target="_blank">查看资源</a>
                                </div>
                            `;
                        });
                        resultsDiv.innerHTML = html;
                    } else {
                        resultsDiv.innerHTML = '<p>未找到相关资源</p>';
                    }
                })
                .catch(error => {
                    resultsDiv.innerHTML = '<p>搜索失败，请重试</p>';
                    console.error('搜索错误:', error);
                });
        }
    </script>
</body>
</html>
"""


@app.route('/')
def home():
    return render_template_string(HTML_CONTENT)


@app.route('/search')
def search():
    name = request.args.get('name', '').strip()

    if not name:
        return jsonify({'error': '请提供搜索关键词'}), 400

    # 模拟搜索结果
    sample_results = [
        {
            "name": f"{name} - 示例资源1",
            "url": "https://pan.baidu.com/s/example1",
            "source": "百度网盘"
        },
        {
            "name": f"{name} - 示例资源2",
            "url": "https://pan.quark.cn/s/example2",
            "source": "夸克网盘"
        }
    ]

    return jsonify({
        "data": sample_results,
        "pagination": {
            "current_page": 1,
            "total_count": len(sample_results)
        }
    })


@app.route('/health')
def health():
    return jsonify({"status": "healthy"})


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=False)